﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xpus.YouYTube.Data;
using Xpus.YouYTube.Utility;
using Xpus.YouYTube.WebSite.Models;

namespace Xpus.YouYTube.WebSite.Controllers
{
	public class VideoController : Controller
	{
		public ActionResult View(int id)
		{
			using (TDataContext db = new TDataContext())
			{
				// 获取对应的视频
				TVideo video = db.TVideos.FirstOrDefault(v => v.Id == id && v.IsDeleted == false);

				if (video == null)
					return RedirectToAction("Index", "Home");

				// 取得上一条和下一条视频
				TVideo prevVideo = db.TVideos.Where(v => v.Id < id && v.Id > (id - 10) && v.IsDeleted == false).OrderByDescending(v => v.Id).FirstOrDefault();
				TVideo nextVideo = db.TVideos.Where(v => v.Id > id && v.Id < (id + 10) && v.IsDeleted == false).FirstOrDefault();

				ViewData["PrevVideo"] = prevVideo;
				ViewData["NextVideo"] = nextVideo;
				ViewData["Video"] = video;
			}

			return View("ViewVideo");
		}

		public ActionResult List(TVideoListType by, int pageIndex, int pageSize)
		{
			int totalVideos = 0;
			int totalPages = 0;
			TVideoWithCommentNumber[] videos = null;

			using (TDataContext db = new TDataContext())
			{
				totalVideos = db.TVideos.Select(v => v.Id).Count();
				totalPages = (totalVideos + pageSize - 1) / pageSize;

				int skip = (pageIndex - 1) * pageSize;
				int take = pageSize;

				switch (by)
				{
					case TVideoListType.ByTime: videos = db.TVideoWithCommentNumbers.OrderByDescending(v => v.AddedTime).Skip(skip).Take(take).ToArray(); break;
					case TVideoListType.ByAgreeNumber: videos = db.TVideoWithCommentNumbers.OrderByDescending(v => v.AgreeNumber).Skip(skip).Take(take).ToArray(); break;
					case TVideoListType.ByDisagreeNumber: videos = db.TVideoWithCommentNumbers.OrderByDescending(v => v.DisagreeNumber).Skip(skip).Take(take).ToArray(); break;
					case TVideoListType.ByCommentNumber: videos = db.TVideoWithCommentNumbers.OrderByDescending(v => v.CommentNumber).Skip(skip).Take(take).ToArray(); break;
					default: return Redirect("/Video/List/ByTime/");
				}

				ViewData["Videos"] = videos;
				ViewData["ListType"] = by.GetFriendlyName();
				ViewData["ListBy"] = by.ToString();
				ViewData["PageIndex"] = pageIndex;
				ViewData["PageSize"] = pageSize;
				ViewData["TotalPages"] = totalPages;

				return View("VideoList");
			}
		}

		public ActionResult Recommend()
		{
			return View("RecommendVideo");
		}

		public ActionResult RecommendSubmit(
			string txtUserName, string txtUserUrl,
			string txtTitle, string txtDescription, string txtSource, string txtEmbeddedCode)
		{
			if (TIpUtility.IsIpBlocked(Request.UserHostAddress, true))
				return Json(new { IsError = true, Message = "对不起，您的IP地址已被屏蔽！您不能推荐视频。" });

			if (txtUserName == null || ((txtUserName = txtUserName.Trim()) == ""))
				return Json(new { IsError = true, Message = "请留下您的大名呗？" });

			if (txtTitle == null || ((txtTitle = txtTitle.Trim()) == ""))
				return Json(new { IsError = true, Message = "这么精彩的视频，不写个标题么？" });

			if (txtDescription == null || ((txtDescription = txtDescription.Trim()) == ""))
				return Json(new { IsError = true, Message = "这么精彩的视频，不简单介绍两句么？" });

			if (txtSource == null || ((txtSource = txtSource.Trim()) == ""))
				return Json(new { IsError = true, Message = "人家添加视频也不容易，把人家的链接地址填进来吧！" });

			if (txtEmbeddedCode == null || ((txtEmbeddedCode = txtEmbeddedCode.Trim()) == ""))
				return Json(new { IsError = true, Message = "您不填写嵌入代码，视频怎么能播放呢？" });

			try
			{
				using (TDataContext db = new TDataContext())
				{
					TUserRecommend recommend = new TUserRecommend()
					{
						Title = txtTitle,
						Description = txtDescription,
						Source = txtSource,
						EmbeddedCode = txtEmbeddedCode,
						UserName = txtUserName,
						UserUrl = txtUserUrl == null ? "" : txtUserUrl.Trim(),
						AddedTime = DateTime.Now,
						UserIp = Request.UserHostAddress,
					};

					db.TUserRecommends.InsertOnSubmit(recommend);
					db.SubmitChanges();
				}

				return Json(new { IsError = false, Message = "提交成功。谢谢您的推荐！" });
			}
			catch
			{
				return Json(new { IsError = true, Message = "抱歉，发生了未知错误！" });
			}
		}
	}
}
